package daq_control

import (
	"context"
	"daqctl/internal/config"
	"fmt"
	"time"

	logr "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

const (
	Command string = "command"
	start   string = "start"
	stop    string = "stop"
)

// AppControl 向daq app发送命令
func AppControl(cmd *cobra.Command, args []string) {
	commandName, err := cmd.Flags().GetString(Command)
	cobra.CheckErr(err)
	if commandName != start && commandName != stop {
		logr.Errorf("%s is invalid, command should be %s or %s", commandName, start, stop)
	}

	ctx := context.Background()

	if commandName == start {
		// 发送start_timestamp
		startTimeKey := fmt.Sprintf("df:%s.start_timestamp", config.DaqCtlConfig.Partition)
		config.RedisCli.Set(ctx, startTimeKey, time.Now().UnixNano(), 0)
	}

	res, err := config.RedisCli.Publish(ctx, config.RedisChannel, commandName).Result()
	if err != nil {
		logr.Errorf("Can not connect to redis: %s", err.Error())
		return
	}

	if res == 0 {
		logr.Errorf("Send %s command failed: no app receive command", commandName)
	} else {
		logr.Infof("Send %s command success: %d apps receive command", commandName, res)
	}
}
